// BOM管理主页面
<script setup lang="ts">
// 导入BOM表单子组件
import BomForm from './components/DetailForm.vue'

// 导入所需的Vue组件和工具函数
import { nextTick, onMounted, onUnmounted, reactive, ref, computed } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'

// 导入报价单相关的类型定义和API
import {
  Quotation,
  QuotationListParam,
  QuotationShare,
  QuotationUpdateStatus,
  QuotationPrintl,
  QuotationDetailVo
} from '@/api/quotation/type.ts'
import {
  getListApi,
  updateStatusApi,
  updateQuotationShareApi,
  printQuotationApi
} from '@/api/quotation/index.ts'

// 导入项目相关的类型定义和API
import { ProjectDocument, ProjectDocumentListParam } from "@/api/project/type.ts"
import { getProjectDocumentListApi } from "@/api/project"

// 导入历史报价单相关API
import { saveStructureQuotationApi } from "@/api/historicalQuotation"

// 导入图标组件
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete,
  Money,
  Document,
} from '@element-plus/icons-vue'

import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import useInstance from '@/hooks/useInstance'
// 使用dialog钩子获取弹窗控制方法
const { dialog, onShow, onClose } = useDialog()
const { global } = useInstance()

// 定义表格高度，用于自适应布局
const tableHeight = ref(0)

// 表格数据相关的响应式变量
const tableData = ref([]) // 表格数据
const loading = ref(false) // 加载状态
// 分页相关数据
const paginationData = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})

// 查询表单对象
const searchForm = reactive(<QuotationListParam>{
  projectId: undefined,
  activate: undefined,
})

// 修改报价单的状态
const updateStatus = reactive(<QuotationUpdateStatus>{
  id: undefined, // 报价单ID
  activate: undefined, // 状态
})

// 分摊金额参数
const quotationShare = reactive(<QuotationShare>{
  ids: [], // 选中的报价单
  type: undefined, // 分摊类型
  price: undefined, // 分摊金额
})

// 查询方法 - 重置页码并获取数据
const search = () => {
  paginationData.currentPage = 1
  getTableData()
}

// 重置查询条件
const reset = () => {
  searchForm.projectId = undefined
  searchForm.activate = undefined
  selectedProject.value = null
  search()
}

// 获取表格数据的核心方法
const getTableData = async () => {
  loading.value = true
  try {
    // 设置分页参数
    searchForm.page = paginationData.currentPage
    searchForm.limit = paginationData.pageSize
    // 调用API获取数据
    let res = await getListApi(searchForm)
    if (res && res.data) {
      tableData.value = res.data.list
      paginationData.total = res.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 生命周期钩子 - 组件挂载时初始化数据和设置表格高度
onMounted(() => {
  getTableData()
  nextTick(() => {
    tableHeight.value = window.innerHeight - 268
  })
})

// 监听窗口大小变化，动态调整表格高度
const handleResize = () => {
  nextTick(() => {
    tableHeight.value = window.innerHeight - 260
  })
}

// 组件挂载时添加窗口大小变化监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 报价单表单显示控制
const showForm = ref(false) // 控制表单显示/隐藏
const formMode = ref<string>('add') // 表单模式：add/edit/view
const Id = ref<number>() // 当前操作的报价单 ID

// 新增BOM
const handleAdd = () => {
  formMode.value = 'add'
  Id.value = undefined
  showForm.value = true
}

// 编辑BOM
const handleEdit = (row: any) => {
  formMode.value = 'edit'
  Id.value = row.id
  showForm.value = true
}

// 查看BOM详情
const handleView = (row: any) => {
  formMode.value = 'view'
  Id.value = row.id
  showForm.value = true
}

// 保存成功后的回调
const handleSaveSuccess = () => {
  showForm.value = false
  getTableData()
}

// 取消操作
const handleCancel = () => {
  showForm.value = false
}

// 激活 作废
const activateChange = async (val: boolean, id: number) => {
  updateStatus.id = id
  updateStatus.activate = val
  try {
    const result = await updateStatusApi(updateStatus)
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

import { getListApi as getColorListApi } from '@/api/color'
import { getListApi as getCustomerListApi } from '@/api/companyCustomer'
import type { Color } from '@/api/color/type'
import type { CompanyCustomer } from '@/api/companyCustomer/type'
import ArchiveSelector from '@/components/common/ArchiveSelector.vue'

// 项目选择器相关数据
const projectSelectorVisible = ref(false)
const selectedProject = ref<ProjectDocument | null>(null)
// 项目状态映射
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '已暂停' },
  { value: 3, label: '已取消' },
]
// 项目选择器搜索字段配置
const projectSearchFields = [
  { label: '项目名称', prop: 'name', type: 'input' as const },
  { label: '项目编号', prop: 'code', type: 'input' as const },
  { label: '客户名称', prop: 'customer', type: 'input' as const },
  {
    label: '项目状态',
    prop: 'status',
    type: 'select' as const,
    options: statusOptions,
  },
]

// 项目选择器表格列配置
const projectTableColumns = [
  { prop: 'name', label: '项目名称', width: 250 },
  { prop: 'code', label: '项目编号', width: 250 },
  { prop: 'customer', label: '客户名称', width: 250 },
  { prop: 'manager', label: '项目经理', width: 200 },
]

// 获取项目列表数据的API方法
const getProjectList = async (params: any) => {
  try {
    // 构建查询参数
    const queryParams: ProjectDocumentListParam = {
      name: params.name,
      code: params.code,
      customer: params.customer,
      status: params.status,
      page: params.page || 1,
      limit: params.limit || 10,
    }

    // 调用项目列表API - 使用真实API
    return await getProjectDocumentListApi(queryParams)
  } catch (error) {
    console.error('获取项目列表失败:', error)
    return { data: { list: [], total: 0 } }
  }
}

// 打开项目选择器
const openProjectSelector = () => {
  projectSelectorVisible.value = true
}

// 处理项目选择确认
const handleProjectSelect = (project: ProjectDocument) => {
  selectedProject.value = project
  console.log('选择的项目:', project)
  searchForm.projectId = project.id
}
// 表格多选选中数据
const multipleSelection = ref<any[]>([])

// 表格多选事件
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  quotationShare.ids = val.map((item) => item.id).filter(Boolean) as number[]
}

// 分摊类型选项
const shareTypes = [
  { label: '包装费', value: 1 },
  { label: '运输费', value: 2 },
  { label: '实施费', value: 3 },
  { label: '其他运营成本', value: 4 },
]

// 显示分摊弹框
const showShareDialog = () => {
  if (quotationShare.ids.length === 0) {
    ElMessage.warning('请先选择需要分摊的报价单')
    return
  }
  dialog.title = '分摊费用'
  dialog.width = 500
  dialog.height = 250
  dialog.visible = true
}

// 提交分摊
const submitShare = async () => {
  if (!quotationShare.type) {
    ElMessage.warning('请选择分摊类型')
    return
  }
  if (!quotationShare.price) {
    ElMessage.warning('请输入分摊金额')
    return
  }
  try {
    await updateQuotationShareApi(quotationShare)
    ElMessage.success('分摊成功')
    dialog.visible = false
    // 重置表单
    quotationShare.type = undefined
    quotationShare.price = undefined
    // 刷新列表
    getTableData()
  } catch (error) {
    console.error('分摊失败:', error)
  }
}

// 添加报价单弹窗相关状态
const quotationDialog = reactive({
  visible: false,
  title: '报价单',
  width: 900,
  height: 600,
  projectId: undefined as number | undefined // 添加projectId字段
})

// 当前报价单信息
const quotationPrintl = ref<QuotationPrintl | null>(null)

// 格式化金额为大写中文
const convertToChinese = (money: number) => {
  if (money === 0) {
    return '零元整'
  }
  
  const fraction = ['角', '分']
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟']
  ]
  const head = money < 0 ? '负' : ''
  
  money = Math.abs(money)
  
  let s = ''
  
  for (let i = 0; i < fraction.length; i++) {
    s += (digit[Math.floor(money * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '')
  }
  
  s = s || '整'
  
  money = Math.floor(money)
  
  for (let i = 0; i < unit[0].length && money > 0; i++) {
    let p = ''
    for (let j = 0; j < unit[1].length && money > 0; j++) {
      p = digit[money % 10] + unit[1][j] + p
      money = Math.floor(money / 10)
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
  }
  
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整')
}

// 格式化金额为货币格式
const formatCurrency = (value: number) => {
  return '¥' + value.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 打印报价单方法
const printQuotation = () => {
  const printWindow = window.open('', 'PRINT', 'height=800,width=1200')
  if (!printWindow) {
    ElMessage.error('无法打开打印窗口，请检查浏览器设置')
    return
  }
  
  // 获取logo的完整URL
  const logoURL = new URL('../../../assets/logo.png', import.meta.url).href
  
    // 创建表格行HTML
    let tableRowsHtml = ''
    const items = quotationPrintl.value?.children || []
    
    items.forEach((item, index) => {
      tableRowsHtml += `
        <tr>
          <td>${index + 1}</td>
          <td>${item.name || ''}</td>
          <td>${item.specification || ''}</td>
          <td>${item.quantity || ''}</td>
          <td>${item.unit || ''}</td>
          <td>¥ ${item.unitPrice ? item.unitPrice.toFixed(2) : '0.00'}</td>
          <td>${item.totalPrice ? item.totalPrice.toFixed(2) : '0.00'}</td>
          <td>${item.remark || ''}</td>
        </tr>
      `
    })
    
    // 计算总金额
    const totalPrice = items.reduce((sum, item) => sum + (item.totalPrice || 0), 0)
    // 总金额大写
    const totalPriceInChinese = convertToChinese(totalPrice)
    
    const currentDate = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/')
    
  // 构建打印内容
  let printContent = `
      <html>
        <head>
          <title>报价单</title>
          <style>
            body { 
              width: 100%; 
              margin: 0; 
              padding: 0;
              font-family: SimSun, serif;
            }
            .quotation-wrapper {
              padding: 20px;
              max-width: 900px;
              margin: 0 auto;
            }
            .quotation-header {
              position: relative;
              margin-bottom: 20px;
              text-align: center;
            }
            .company-logo {
              position: absolute;
              top: 0;
              right: 0;
              text-align: right;
            }
            .company-logo img {
              max-width: 80px;
              height: auto;
            }
            .company-title {
              font-size: 20px;
              font-weight: bold;
              margin-bottom: 10px;
            }
            .document-title {
              font-size: 22px;
              font-weight: bold;
              margin-bottom: 5px;
            }
            .document-info {
              display: flex;
              justify-content: space-between;
              width: 100%;
            }
            .document-number {
              font-weight: bold;
            }
            .document-date {
              font-size: 14px;
            }
            .certification-info {
              text-align: center;
              color: #e41e2b;
              font-size: 14px;
              margin-bottom: 15px;
              border-bottom: 1px solid #dcdfe6;
              padding-bottom: 10px;
            }
            .info-section {
              margin-bottom: 15px;
            }
            .info-table {
              width: 100%;
              border-collapse: collapse;
              margin-bottom: 15px;
            }
            .info-table td {
              padding: 8px;
              border: 1px solid #000;
            }
            .info-table .label {
              width: 17%;
              text-align: right;
              font-weight: bold;
            }
            .info-table .value {
              width: 35%;
            }
            .note-section {
              margin-bottom: 15px;
            }
            .note-label {
              font-weight: bold;
              margin-bottom: 5px;
            }
            .note-content {
              border: 1px solid #000;
              padding: 10px;
            }
            .note-row {
              display: flex;
              margin-bottom: 10px;
            }
            .note-title {
              font-weight: bold;
              width: 150px;
            }
            .items-section {
              margin-bottom: 15px;
            }
            .quotation-table {
              margin: 16px 0;
              font-size: 12px;
              width: 100%;
              border-collapse: collapse;
            }
            .quotation-table th,
            .quotation-table td {
              padding: 6px;
              border: 1px solid #000;
              text-align: center;
            }
            .quotation-table thead th {
              background-color: #f0f0f0;
              font-weight: bold;
            }
            .quotation-table .total-row {
              background-color: #f0f0f0;
              font-weight: bold;
            }
            .quotation-table .total-row .text-right {
              text-align: right;
            }
            .terms-section {
              margin-top: 15px;
            }
            .terms-list {
              margin-left: 20px;
              padding-left: 0;
            }
            .terms-list li {
              margin-bottom: 5px;
              font-size: 14px;
            }
            .terms-note {
              margin-top: 10px;
              font-size: 14px;
            }
            .quotation-footer {
              margin-top: 24px;
              padding-top: 16px;
              border-top: 1px solid #ebeef5;
              display: flex;
              justify-content: flex-end;
            }
            .print-area {
              display: none !important;
              visibility: hidden !important;
            }
            .total-amount {
              margin-left: auto;
              font-size: 16px;
              font-weight: bold;
              color: #303133;
              text-align: right;
            }
            .el-button {
              display: none !important;
            }
          </style>
        </head>
        <body>
          <div class="quotation-wrapper">
            <div class="quotation-header">
              <div class="company-logo">
                <img src="${logoURL}" alt="公司logo" class="logo-image">
              </div>
              <div class="company-title">
                浙江中扬立库技术有限公司
              </div>
              <div class="document-title">
                报价单
              </div>
                <div class="document-info">
                <div class="document-date"> </div>
                <div class="document-number">NO.${ Math.floor(Math.random() * 1000) + 1 }</div>
              </div>
              <div class="document-info">
                <div class="document-number"> </div>
                <div class="document-date">日期：${currentDate}</div>
              </div>
            </div>
            
            <!-- 公司认证信息 -->
            <div class="certification-info">
              本公司专业生产制造现代仓储物流系统设备，已通过ISO9001质量体系认证、环境管理体系ISO14001
            </div>
            
            <!-- 客户与公司信息 -->
            <div class="info-section">
              <table class="info-table" border="1" cellspacing="0" cellpadding="0">
                <tr>
                  <td class="label">客户名称：</td>
                  <td class="value">${quotationPrintl.value?.customerName || ''}</td>
                  <td class="label">公司：</td>
                  <td class="value">浙江中扬立库技术有限公司</td>
                </tr>
                <tr>
                  <td class="label">联系人：</td>
                  <td class="value">${quotationPrintl.value?.customerPerson || ''}</td>
                  <td class="label">联系人：</td>
                  <td class="value">${quotationPrintl.value?.person || ''}</td>
                </tr>
                <tr>
                  <td class="label">联系方式：</td>
                  <td class="value">${quotationPrintl.value?.customerPhone || ''}</td>
                  <td class="label">联系方式：</td>
                  <td class="value">${quotationPrintl.value?.pPhone || ''}</td>
                </tr>
                <tr>
                  <td class="label">地址：</td>
                  <td class="value">${quotationPrintl.value?.customerAddress || ''}</td>
                  <td class="label">地址：</td>
                  <td class="value">${quotationPrintl.value?.address || ''}</td>
                </tr>
                <tr>
                  <td class="label">传真：</td>
                  <td class="value">${quotationPrintl.value?.customerFax || ''}</td>
                  <td class="label">传真：</td>
                  <td class="value">${quotationPrintl.value?.fax || ''}</td>
                </tr>
                <tr>
                  <td class="label">邮箱：</td>
                  <td class="value">${quotationPrintl.value?.customerEmail || ''}</td>
                  <td class="label">邮箱：</td>
                  <td class="value">${quotationPrintl.value?.email || ''}</td>
                </tr>
              </table>
            </div>
            
            <!-- 备注区域 -->
            <div class="note-section">
              <div class="note-label">备注</div>
              <div class="note-content">
                <div class="note-row">
                  <div class="note-title">货物参数：</div>
                </div>
                <div class="note-row">
                  <div class="note-title">货物简要描述：</div>
                </div>
              </div>
            </div>
            
            <!-- 商品清单 -->
            <div class="items-section">
              <table class="quotation-table" border="1" cellspacing="0" cellpadding="0">
                <thead>
                  <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>规格型号</th>
                    <th>数量</th>
                    <th>单位</th>
                    <th>单价</th>
                    <th>小计</th>
                    <th>备注</th>
                  </tr>
                </thead>
                <tbody>
                  ${tableRowsHtml}
                  <tr class="total-row">
                    <td colspan="2" class="text-right">总计大写：</td>
                    <td colspan="3">${totalPriceInChinese}</td>
                    <td>总计金额：</td>
                    <td colspan="2">${formatCurrency(totalPrice)}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            
            <!-- 报价条款 -->
            <div class="terms-section">
              <ol class="terms-list">
                <li>以上报价根据国家税率涨幅含增值税发票；</li>
                <li>材质：Q355/Q235。强度标准：GB/50018-2016，屈服强度—235(N/mm2)  抗拉—205(N/mm2)  伸长率31%</li>
                <li>表面处理：脱脂磷化，后采用优质环氧树脂瑞士金马静电喷涂，执行标准：GB 15607-2008</li>
                <li>焊接标准.焊接标准：抗压—300(N/mm2) 抗拉—255(N/mm2) 抗剪—175(N/mm2)</li>
                <li>制造执行标准：CECS23-90(货架设计规范)；Jb/t5323-1991 (钢货架技术条件)；GBJ50017-2003 （高位仓库货架设计标准）；GBT 30675-2014 （阁楼式货架）</li>
                <li>报价单有效期：由于钢材价格波动比较大，此报价有效期：3天。</li>
                <li>钢材供应商；宝钢 日照钢铁 鞍钢 首钢及国内大型钢厂</li>
                <li>保修期：非人为因素保修1年</li>
                <li>付款方式：预付40%，发货付40%，全部到货验收后30天内付20%。</li>
                <li>以上报价按抗震6度计算，地震加速度为0.05g;</li>
              </ol>
              <div class="terms-note">
                注：付款方式为电汇，如承兑付款收取承兑汇票2.5%财务费用（半年期），乙方不接受商业承兑汇票。
              </div>
            </div>
          </div>
        </body>
      </html>
  `
  
  printWindow.document.write(printContent)
    printWindow.document.close()
    printWindow.focus()
    printWindow.print()
    printWindow.close()
    quotationDialog.visible = false
}

// 生成报价单方法
const generateQuotation = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择需要生成报价单的记录')
    return
  }
  
  try {
    // 获取选中项目的ID
    // 直接从勾选的核价单中获取项目ID
    // 优先使用第一个选中项目的projectId
    let projectId: number | undefined
    
    // 1. 先检查选中项中是否有projectId字段
    const firstItem = multipleSelection.value[0]
    if (firstItem && firstItem.projectId) {
      projectId = firstItem.projectId
    } 
    // 2. 如果没有，尝试从projectName找到对应的项目
    else if (firstItem && firstItem.projectName) {
      // 可能需要从表格数据中查找完整的项目信息
      // 或者使用查询条件中的项目ID
      projectId = searchForm.projectId
    }
    // 3. 如果上述都没有，尝试使用已选择的项目
    else if (selectedProject.value && selectedProject.value.id) {
      projectId = selectedProject.value.id
    }
    
    if (!projectId) {
      ElMessage.warning('未能获取到项目ID，请先选择项目')
      return
    }
    
    // 记录获取的项目ID，用于后续保存操作
    quotationDialog.projectId = projectId
    
    // 获取报价单ID列表
    const ids = multipleSelection.value.map(item => item.id).filter(Boolean)
    if (ids.length === 0) {
      ElMessage.warning('未获取到有效的ID列表')
      return
  }
  
    console.log('生成报价单，使用项目ID:', projectId, '选中的报价单IDs:', ids)
    
    // 调用报价单打印API
    const res = await printQuotationApi(ids)
    if (res.code === 200 && res.data) {
      quotationPrintl.value = res.data
      quotationDialog.visible = true
    } else {
      ElMessage.error(res.msg || '生成报价单失败')
    }
  } catch (err) {
    console.error('生成报价单异常', err)
    ElMessage.error('生成报价单失败')
  }
}

// 添加保存报价单方法
const saveQuotation = async () => {
  if (!quotationPrintl.value) {
    ElMessage.warning('无报价单数据，无法保存')
    return
  }

  // 获取打印内容
  const contentElement = document.getElementById('quotationContent')
  if (!contentElement) {
    ElMessage.error('获取报价单内容失败')
    return
  }

  // 构建完整的HTML内容，包含样式
  const styleContent = `
    <style>
      body { font-family: SimSun, serif; margin: 0; padding: 0; text-align: center; }
      .quotation-wrapper {
        padding: 20px;
        max-width: 900px;
        margin: 0 auto;
      }
      .quotation-header {
        position: relative;
        margin-bottom: 20px;
        text-align: center;
      }
      .company-logo {
        position: absolute;
        top: 0;
        right: 0;
        text-align: right;
      }
      .company-logo img {
        max-width: 80px;
        height: auto;
      }
      .company-title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 10px;
      }
      .document-title {
        font-size: 22px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      .document-info {
        display: flex;
        justify-content: space-between;
        width: 100%;
      }
      .document-number {
        font-weight: bold;
      }
      .document-date {
        font-size: 14px;
      }
      .certification-info {
        text-align: center;
        color: #e41e2b;
        font-size: 14px;
        margin-bottom: 15px;
        border-bottom: 1px solid #dcdfe6;
        padding-bottom: 10px;
      }
      .info-section {
        margin-bottom: 15px;
      }
      .info-table {
        width: 100%;
        border-collapse: collapse;
        margin-bottom: 15px;
      }
      .info-table td {
        padding: 8px;
        border: 1px solid #000;
      }
      .info-table .label {
        width: 17%;
        text-align: right;
        font-weight: bold;
      }
      .info-table .value {
        width: 35%;
      }
      .note-section {
        margin-bottom: 15px;
      }
      .note-label {
        font-weight: bold;
        margin-bottom: 5px;
      }
      .note-content {
        border: 1px solid #000;
        padding: 10px;
      }
      .note-row {
        display: flex;
        margin-bottom: 10px;
      }
      .note-title {
        font-weight: bold;
        width: 150px;
      }
      .items-section {
        margin-bottom: 15px;
      }
      .quotation-table {
        margin: 16px 0;
        font-size: 12px;
        width: 100%;
        border-collapse: collapse;
      }
      .quotation-table th,
      .quotation-table td {
        padding: 6px;
        border: 1px solid #000;
        text-align: center;
      }
      .quotation-table thead th {
        background-color: #f0f0f0;
        font-weight: bold;
      }
      .quotation-table .total-row {
        background-color: #f0f0f0;
        font-weight: bold;
      }
      .quotation-table .total-row .text-right {
        text-align: right;
      }
      .terms-section {
        margin-top: 15px;
      }
      .terms-list {
        margin-left: 20px;
        padding-left: 0;
      }
      .terms-list li {
        margin-bottom: 5px;
        font-size: 14px;
      }
      .terms-note {
        margin-top: 10px;
        font-size: 14px;
      }
      .quotation-footer {
        margin-top: 24px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: flex-end;
      }
      .print-area {
        display: none !important;
        visibility: hidden !important;
      }
      .total-amount {
        margin-left: auto;
        font-size: 16px;
        font-weight: bold;
        color: #303133;
        text-align: right;
      }
      .el-button {
        display: none !important;
      }
    </style>
  `
  
  // 获取内容并移除按钮
  let htmlContent = contentElement.innerHTML
  // 将按钮部分替换为空
  htmlContent = htmlContent.replace(/<div class="quotation-footer">[\s\S]*?<\/div>/g, '')
  
  // 完整的HTML文档
  const fullContent = `
    <div class="quotation-wrapper">
      ${htmlContent}
    </div>
    ${styleContent}
  `
  
  // 获取项目ID - 优先使用生成报价单时保存的项目ID
  let projectId = quotationDialog.projectId
  
  // 如果没有保存的项目ID，尝试从勾选的核价单获取
  if (!projectId && multipleSelection.value.length > 0) {
    const firstItem = multipleSelection.value[0]
    if (firstItem && firstItem.projectId) {
      projectId = firstItem.projectId
    }
  }
  
  // 如果上述方法都没获取到，尝试从其他地方获取
  if (!projectId) {
    // 尝试从查询表单获取
    if (searchForm.projectId) {
      projectId = searchForm.projectId
    }
    // 尝试从已选择的项目获取
    else if (selectedProject.value && selectedProject.value.id) {
      projectId = selectedProject.value.id
    }
  }
  
  // 最后验证是否获取到项目ID
  if (!projectId) {
    ElMessage.warning('未能获取到项目ID，请重新选择项目后再试')
    return
  }
  
  console.log('保存报价单，使用项目ID:', projectId)
  
  // 构建保存数据
  const saveData = {
    projectId: projectId,
    content: fullContent
  }
  
  // 调用保存API
  try {
    const res = await saveStructureQuotationApi(saveData)
    if (res.code === 200) {
      ElMessage.success('报价单保存成功')
      quotationDialog.visible = false
    } else {
      ElMessage.error(res.msg || '保存报价单失败')
    }
  } catch (err) {
    console.error('保存报价单失败', err)
    ElMessage.error('保存报价单失败')
  }
}

</script>

<template>
  <!-- 左侧列表 -->
  <el-main v-if="!showForm">
    <el-card class="search-card">
      <!-- 搜索表单 -->
      <el-form :inline="true"
               :model="searchForm">
        <el-form-item label="项目名称">
          <el-input   :model-value="selectedProject ? selectedProject.name : ''"
                    placeholder="选择项目"
                    readonly>
            <template #append>
              <el-button @click="openProjectSelector">选择</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.activate"
                     placeholder="是否生效"
                     clearable
                     style="width: 110px">
            <el-option label="生效"
                       :value="1" />
            <el-option label="作废"
                       :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="search">
            <el-icon>
              <Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="reset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
          <el-button type="success"
                     @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增
          </el-button>
          <el-button type="warning"
                     @click="showShareDialog"
                     :disabled="!quotationShare.ids.length">
            <el-icon>
              <Money />
            </el-icon>
            分摊费用
          </el-button>
          <el-button
            type="info"
            @click="generateQuotation"
            :disabled="!multipleSelection.length">
            <el-icon>
              <Document />
            </el-icon>
            生成报价单
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格 -->
    <el-table :loading="loading"
              :data="tableData"
              border
              :height="tableHeight"
              style="width: 100%;margin-top: 15px"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"
                       width="55" />
      <el-table-column type="index"
                       label="序号"
                       width="70" />
      <el-table-column prop="项目名称"
                       label="项目名称"
                       min-width="180">
        <template #default="scope">
          <el-tag type="primary">{{scope.row.projectName}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="name"
                       label="名称"
                       min-width="120" />
      <el-table-column prop="specification"
                       label="规格"
                       min-width="120" />
      <el-table-column prop="material"
                       label="材质"
                       min-width="200" />
      <el-table-column prop="quantity"
                       label="数量"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.quantity }}
        </template>
      </el-table-column>
      <el-table-column prop="unit"
                       label="单位"
                       min-width="150" />
      <el-table-column prop="remark"
                       label="备注"
                       min-width="100" />
      <el-table-column prop="unitPrice"
                       label="含税单价"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.unitPrice ? scope.row.unitPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="unitWeight"
                       label="单重"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.unitWeight ? scope.row.unitWeight.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="kgPrice"
                       label="公斤价"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.kgPrice ? scope.row.kgPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="totalPrice"
                       label="总价"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.totalPrice ? scope.row.totalPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="totalWeight"
                       label="总重"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.totalWeight ? scope.row.totalWeight.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>

      <el-table-column prop="packingPrice"
                       label="包装费"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.packingPrice ? scope.row.packingPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>

      <el-table-column prop="transportationPrice"
                       label="运输费"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.transportationPrice ? scope.row.transportationPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>

      <el-table-column prop="implementationPrice"
                       label="实施费"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.implementationPrice ? scope.row.implementationPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>

      <el-table-column prop="otherPrice"
                       label="其他费用"
                       min-width="100">
        <template #default="scope">
          {{ scope.row.otherPrice ? scope.row.otherPrice.toFixed(2) : '0.00' }}
        </template>
      </el-table-column>

      <el-table-column label="操作"
                       width="250"
                       fixed="right">
        <template #default="scope">
          <el-button type="success"
                     size="small"
                     link
                     @click="handleEdit(scope.row)"
                     icon="Edit">编辑</el-button>
          <el-button type="primary"
                     size="small"
                     link
                     @click="handleView(scope.row)"
                     icon="View">详情</el-button>
          <!--<el-button type="danger" size="small" link @click="deleteOne(scope.row.id)" icon="Delete">删除</el-button>-->
          <el-switch v-model="scope.row.activate"
                     class="ml-2"
                     inline-prompt
                     style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949;margin-left: 15px"
                     active-text="生效"
                     inactive-text="作废"
                     @change="activateChange(scope.row.activate,scope.row.id)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="paginationData.currentPage"
                   v-model:page-size="paginationData.pageSize"
                   :page-sizes="[10, 20, 50]"
                   :total="paginationData.total"
                   layout="total, sizes, prev, pager, next"
                   class="pagination"
                   @size-change="getTableData"
                   @current-change="getTableData" />

    <!-- 分摊费用弹框 -->
    <sys-dialog :title="dialog.title"
                :width="dialog.width"
                :visible="dialog.visible"
                :height="dialog.height"
                @on-close="onClose"
                @on-confirm="submitShare">
      <template #content>
        <div class="share-form">
          <el-form :model="quotationShare"
                   label-width="120px">
            <el-form-item label="分摊类型"
                          required>
              <el-select v-model="quotationShare.type"
                         placeholder="请选择分摊类型"
                         style="width: 100%">
                <el-option v-for="item in shareTypes"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="分摊金额"
                          required>
              <el-input-number v-model="quotationShare.price"
                               :precision="2"
                               :step="0.1"
                               :min="0"
                               style="width: 100%"
                               placeholder="请输入分摊金额" />
            </el-form-item>
          </el-form>
        </div>
      </template>
    </sys-dialog>

    <!-- 新增报价单展示弹窗 -->
    <sys-dialog
      :title="quotationDialog.title"
      :width="quotationDialog.width"
      :visible="quotationDialog.visible"
      :height="quotationDialog.height"
      @on-close="quotationDialog.visible = false" style="width: 730px;">
      <template #content>
        <div id="quotationContent">
          <div class="quotation-header">
            <div class="company-logo">
              <img src="../../../assets/logo.png" alt="公司logo" class="logo-image">
            </div>
            <div class="company-title">
              浙江中扬立库技术有限公司
            </div>
          </div>
          <div class="document-title">
            报价单
          </div>
          <div class="document-info">
          <div class="document-number"></div>
          <div class="document-number">NO.{{ Math.floor(Math.random() * 1000) + 1 }}</div>
          </div>
          <div class="document-info">
            <div class="document-number"></div>
            <div class="document-date">日期：{{ new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '/') }}</div>
          </div>

          <!-- 公司认证信息 -->
          <div class="certification-info">
            本公司专业生产制造现代仓储物流设备，已通过ISO9001质量体系认证，环境管理体系ISO14001
          </div>
          
          <!-- 客户与公司信息 -->
          <div class="info-section">
            <table class="info-table" border="1" cellspacing="0" cellpadding="0">
              <tr>
                <td class="label">客户名称：</td>
                <td class="value">{{ quotationPrintl?.customerName || '' }}</td>
                <td class="label">公司：</td>
                <td class="value">浙江中扬立库技术有限公司</td>
              </tr>
              <tr>
                <td class="label">联系人：</td>
                <td class="value">{{ quotationPrintl?.customerPerson || '' }}</td>
                <td class="label">联系人：</td>
                <td class="value">{{ quotationPrintl?.person || '' }}</td>
              </tr>
              <tr>
                <td class="label">联系方式：</td>
                <td class="value">{{ quotationPrintl?.customerPhone || '' }}</td>
                <td class="label">联系方式：</td>
                <td class="value">{{ quotationPrintl?.pPhone || '' }}</td>
              </tr>
              <tr>
                <td class="label">地址：</td>
                <td class="value">{{ quotationPrintl?.customerAddress || '' }}</td>
                <td class="label">地址：</td>
                <td class="value">{{ quotationPrintl?.address || '' }}</td>
              </tr>
              <tr>
                <td class="label">传真：</td>
                <td class="value">{{ quotationPrintl?.customerFax || '' }}</td>
                <td class="label">传真：</td>
                <td class="value">{{ quotationPrintl?.fax || '' }}</td>
              </tr>
              <tr>
                <td class="label">邮箱：</td>
                <td class="value">{{ quotationPrintl?.customerEmail || '' }}</td>
                <td class="label">邮箱：</td>
                <td class="value">{{ quotationPrintl?.email || '' }}</td>
              </tr>
            </table>
          </div>
          
          <!-- 备注区域 -->
          <div class="note-section">
            <div class="note-label">备注</div>
            <div class="note-content">
              <div class="note-row">
                <div class="note-title">货物参数：</div>
              </div>
              <div class="note-row">
                <div class="note-title">货物简要描述：</div>
              </div>
            </div>
          </div>
          
          <!-- 商品清单 -->
          <div class="items-section">
            <table class="quotation-table" border="1" cellspacing="0" cellpadding="0">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>名称</th>
                  <th>规格型号</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>单价</th>
                  <th>小计</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in quotationPrintl?.children || []" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item?.name || '' }}</td>
                  <td>{{ item?.specification || '' }}</td>
                  <td>{{ item?.quantity || 0 }}</td>
                  <td>{{ item?.unit || '' }}</td>
                  <td>¥ {{ item?.unitPrice ? item.unitPrice.toFixed(2) : '0.00' }}</td>
                  <td>{{ item?.totalPrice ? item.totalPrice.toFixed(2) : '0.00' }}</td>
                  <td>{{ item?.remark || '' }}</td>
                </tr>
                <!-- 计算总金额 -->
                <tr class="total-row">
                  <td colspan="2" class="text-right">总计大写：</td>
                  <td colspan="3">{{ convertToChinese(quotationPrintl?.children?.reduce((sum, item) => sum + (item?.totalPrice || 0), 0) || 0) }}</td>
                  <td>总计金额：</td>
                  <td colspan="2">{{ formatCurrency(quotationPrintl?.children?.reduce((sum, item) => sum + (item?.totalPrice || 0), 0) || 0) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
          
          <!-- 报价条款 -->
          <div class="terms-section">
            <ol class="terms-list">
                <li>1.以上报价根据国家税率涨幅含增值税发票；</li>
                <li>2.材质：Q355/Q235。强度标准：GB/50018-2016，屈服强度—235(N/mm2)  抗拉—205(N/mm2)  伸长率31%</li>
                <li>3.表面处理：脱脂磷化，后采用优质环氧树脂瑞士金马静电喷涂，执行标准：GB 15607-2008</li>
                <li>4.焊接标准.焊接标准：抗压—300(N/mm2) 抗拉—255(N/mm2) 抗剪—175(N/mm2)</li>
                <li>5.制造执行标准：CECS23-90(货架设计规范)；Jb/t5323-1991 (钢货架技术条件)；GBJ50017-2003 （高位仓库货架设计标准）；GBT 30675-2014 （阁楼式货架）</li>
                <li>6.报价单有效期：由于钢材价格波动比较大，此报价有效期：3天。</li>
                <li>7.钢材供应商；宝钢 日照钢铁 鞍钢 首钢及国内大型钢厂</li>
                <li>8.保修期：非人为因素保修1年</li>
                <li>9.付款方式：预付40%，发货付40%，全部到货验收后30天内付20%。</li>
                <li>10.以上报价按抗震6度计算，地震加速度为0.05g;</li>
              </ol>
              <div class="terms-note">
                注：付款方式为电汇，如承兑付款收取承兑汇票2.5%财务费用（半年期），乙方不接受商业承兑汇票。
              </div>
          </div>
          
          <div class="quotation-footer">
            <el-button type="primary" size="large" @click="printQuotation" style="padding: 12px 24px; font-size: 16px;">
              <el-icon style="margin-right: 5px;"><Document /></el-icon>
              打印报价单
            </el-button>
            <el-button type="success" size="large" @click="saveQuotation" style="padding: 12px 24px; font-size: 16px; margin-left: 10px;">
              <el-icon style="margin-right: 5px;"><Document /></el-icon>
              保存报价单
            </el-button>
          </div>
        </div>
      </template>
    </sys-dialog>
  </el-main>

  <!-- 右侧表单占满整个屏幕 -->
  <el-main v-else>
    <BomForm :Id="Id"
             :mode="formMode"
             @save-success="handleSaveSuccess"
             @cancel="handleCancel" />
  </el-main>

  <!-- 项目选择器组件 -->
  <ArchiveSelector v-model="projectSelectorVisible"
                   title="选择项目"
                   :search-fields="projectSearchFields"
                   :table-columns="projectTableColumns"
                   :fetch-data-api="getProjectList"
                   :multiple="false"
                   @confirm="handleProjectSelect" />
</template>


<style scoped lang="scss">
.el-pagination {
  margin-top: 10px;
  justify-content: flex-end;
}

.search-card {
  height: 70px;
}

.share-form {
  padding: 20px;

  :deep(.el-form-item__label) {
    font-weight: bold;
  }

  :deep(.el-input-number) {
    width: 100%;
  }
}

.quotation-content {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .quotation-header {
    position: relative;
    margin-bottom: 15px;
    text-align: center;
    display: flex;
    flex-direction: column;

    .company-logo {
      position: absolute;
      top: 0;
      right: 0;
      text-align: right;

      .logo-image {
        max-width: 80px;
        height: auto;
      }
    }

    .company-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .document-title {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .document-info {
      display: flex;
      justify-content: space-between;
      width: 100%;

      .document-number {
        font-weight: bold;
      }

      .document-date {
        font-size: 14px;
      }
    }
  }

  .certification-info {
    text-align: center;
    color: #e41e2b;
    font-size: 14px;
    margin-bottom: 15px;
    border-bottom: 1px solid #dcdfe6;
    padding-bottom: 10px;
  }

  .info-section {
    margin-bottom: 15px;

    .info-table {
      width: 100%;
      border-collapse: collapse;

      td {
        padding: 8px;
        border: 1px solid #000;

        &.label {
          width: 15%;
          text-align: right;
          font-weight: bold;
        }

        &.value {
          width: 35%;
        }
      }
    }
  }

  .note-section {
    margin-bottom: 15px;

    .note-label {
      font-weight: bold;
      margin-bottom: 5px;
    }

    .note-content {
      border: 1px solid #000;
      padding: 10px;

      .note-row {
        display: flex;
        margin-bottom: 10px;

        .note-title {
          font-weight: bold;
          width: 150px;
        }
      }
    }
  }

  .items-section {
    margin-bottom: 15px;

    .quotation-table {
      width: 100%;
      border-collapse: collapse;

      th, td {
        padding: 8px;
        border: 1px solid #000;
        text-align: center;
      }

      thead {
        background-color: #f0f0f0;

        th {
          font-weight: bold;
        }
      }

      .total-row {
        background-color: #f0f0f0;
        font-weight: bold;

        .text-right {
          text-align: right;
        }
      }
    }
  }

  .terms-section {
    .terms-list {
      margin-left: 20px;
      padding-left: 0;

      li {
        margin-bottom: 5px;
        font-size: 14px;
      }
    }

    .terms-note {
      margin-top: 10px;
      font-size: 14px;
    }
  }

  .quotation-footer {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .total-amount {
      margin-left: auto; /* 确保总价在右侧 */
      font-size: 18px;
      font-weight: bold;
      color: #303133;
      text-align: right;
    }

    .print-area {
      .el-button {
        padding: 10px 24px;
        font-size: 14px;
      }
    }
  }
}

@media print {
  body {
    width: 100%;
    margin: 0;
    padding: 0;
  }

  .quotation-content {
    padding: 0;
    box-shadow: none;

    .quotation-header {
      .quotation-logo {
        .logo-image {
          max-width: 120px;
        }
      }

      .quotation-date-number {
        display: flex;
        justify-content: space-between;
        width: 100%;

        .date {
          text-align: left;
        }

        .number {
          text-align: right;
        }
      }

      .quotation-info {
        h2 {
          font-size: 20px;
        }
      }
    }

    .quotation-table {
      font-size: 12px;

      th, td {
        padding: 6px;
      }
    }

    .quotation-footer {
      display: flex;
      justify-content: flex-end !important;

      .print-area {
        display: none;
        visibility: hidden;
      }

      .total-amount {
        margin-left: auto;
        text-align: right;
        font-size: 16px;
      }
    }
  }
}

#quotationContent {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  max-width: 900px;
  margin: 0 auto;
  border: 1px solid #dcdfe6;
  font-family: SimSun, serif;
}

.quotation-header {
  position: relative;
  margin-bottom: 20px;
  text-align: center;
}

.company-logo {
  position: absolute;
  top: 0;
  right: 0;
  text-align: right;
}

.company-logo img {
  max-width: 80px;
  height: auto;
}

.action-bar {
  margin-bottom: 20px;
  text-align: right;
  
  @media print {
    display: none;
  }
}

.company-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.document-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.document-info {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.certification-info {
  text-align: center;
  color: #e41e2b;
  font-size: 14px;
  margin-bottom: 15px;
  border-bottom: 1px solid #dcdfe6;
  padding-bottom: 10px;
}

.info-section {
  margin-bottom: 15px;
}

.info-table {
  width: 100%;
  border-collapse: collapse;
}

.info-table td {
  padding: 8px;
  border: 1px solid #000;
}

.info-table .label {
  width: 15%;
  text-align: right;
  font-weight: bold;
}

.info-table .value {
  width: 35%;
}

.note-section {
  margin-bottom: 15px;
}

.note-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.note-content {
  border: 1px solid #000;
  padding: 10px;
}

.note-row {
  display: flex;
  margin-bottom: 10px;
}

.note-title {
  font-weight: bold;
  width: 150px;
}

.items-section {
  margin-bottom: 15px;
}

.quotation-table {
  width: 100%;
  border-collapse: collapse;
}

.quotation-table th, .quotation-table td {
  padding: 8px;
  border: 1px solid #000;
  text-align: center;
}

.quotation-table thead th {
  background-color: #f0f0f0;
  font-weight: bold;
}

.quotation-table .total-row {
  background-color: #f0f0f0;
  font-weight: bold;
}

.quotation-table .total-row .text-right {
  text-align: right;
}

.terms-section {
  margin-top: 15px;
}

.terms-list {
  margin-left: 20px;
  padding-left: 0;
}

.terms-list li {
  margin-bottom: 5px;
  font-size: 14px;
}

.terms-note {
  margin-top: 10px;
  font-size: 14px;
}


</style>
